import os
from datetime import datetime

from docx import Document
from flask import request, render_template, send_file
import re
import logging

#
# def upload_file():
#     if request.method == "POST":
#         file = request.files["file"]
#         if file:
#             filename = file.filename
#             file.save(filename)  # 保存文件到当前目录
#
#             return f"文件 {filename} 上传成功！"

file_path_root = "H:\\"  # windows环境使用


# file_path_root = "/home/will"  # windows环境使用


# file_path_root = "/home/will" # linux环境使用
def upload_files():
    # 获取上传的两个文件
    file1 = request.files['file1']
    file2 = request.files['file2']

    # 保存上传的文件
    file1Path = file_path_root + file1.filename
    file2Path = file_path_root + file2.filename
    file1.save(file1Path)
    file2.save(file2Path)

    # 合并两个文件
    return merge_files(file1, file2)

    # # 返回合并后的文件给用户下载
    # return send_file(merged_file, as_attachment=True)


def merge_files(file1, file2):
    # 打开两个文件
    doc1 = Document(file1)
    doc2 = Document(file2)

    # 合并两个文件的内容
    for element in doc2.element.body:
        doc1.element.body.append(element)

    # window本地，test版本
    # merge_file_name = os.path.splitext(file1)[0] + "_" + os.path.splitext(file2)[0] + "_" + datetime.now().strftime(
    #     '%Y%m%d%H%M%S') + ".docx"
    # merged_file = os.path.join(os.path.dirname(__file__), merge_file_name) # 调用os.path，注意这里与flask版本的区别
    # doc1.save(merged_file)

    # 修改后版本
    merge_file_name = file1.filename.split(".")[0] + "_" + file2.filename.split(".")[0]+ datetime.now().strftime('%Y%m%d%H%M%S') + ".docx"
    merged_file = file_path_root + merge_file_name
    doc1.save(merged_file)

    return merge_file_name

